<template>
  <div class="page-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <el-page-header @back="$router.push('/dashboard')" style="margin-bottom: 20px;">
        <template #content>
          <span style="font-size: 18px; font-weight: 600;">Customer Management</span>
        </template>
      </el-page-header>
    </div>

    <!-- 主要内容 -->
    <div class="main-content">
      <!-- 搜索和操作栏 -->
      <el-card style="margin-bottom: 20px;" shadow="hover">
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <div style="display: flex; gap: 16px; align-items: center;">
            <el-input
              v-model="searchQuery"
              placeholder="Search customer name, email or phone"
              style="width: 300px;"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select v-model="statusFilter" placeholder="Filter by status" style="width: 120px;" clearable>
              <el-option label="All" value="" />
              <el-option label="Active" value="active" />
              <el-option label="Inactive" value="inactive" />
            </el-select>
          </div>
          <div>
            <el-button type="primary" @click="handleAddCustomer">
              <el-icon><Plus /></el-icon>
              Add Customer
            </el-button>
            <el-button @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              Refresh
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 客户列表 -->
      <el-card shadow="hover">
        <template #header>
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <span style="font-size: 16px; font-weight: 600;">Customer List</span>
            <el-text type="info">Total {{ totalCustomers }} customers</el-text>
          </div>
        </template>

        <el-table
          :data="displayCustomers"
          v-loading="loading"
          style="width: 100%"
          stripe
          border
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="username" label="Username" width="150" />
          <el-table-column prop="email" label="Email" width="250" />
          <el-table-column prop="role" label="Role" width="100" />
          <el-table-column label="Status" width="100">
            <template #default="{ row }">
              <el-tag :type="row.isActive ? 'success' : 'danger'">
                {{ row.isActive ? 'Active' : 'Inactive' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="Created At" width="180">
            <template #default="{ row }">
              {{ formatDate(row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column prop="lastLoginAt" label="Last Login" width="180">
            <template #default="{ row }">
              {{ formatDate(row.lastLoginAt) }}
            </template>
          </el-table-column>
          <el-table-column label="Actions" width="280" fixed="right">
            <template #default="{ row }">
              <el-button size="small" @click="handleViewCustomer(row)">
                View
              </el-button>
              <el-button size="small" type="primary" @click="handleEditCustomer(row)">
                Edit
              </el-button>
              <el-button
                size="small"
                :type="row.isActive ? 'warning' : 'success'"
                @click="handleToggleStatus(row)"
              >
                {{ row.isActive ? 'Disable' : 'Enable' }}
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleDeleteCustomer(row)"
              >
                Delete
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div style="margin-top: 20px; display: flex; justify-content: center;">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="totalCustomers"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- Customer Details Dialog -->
    <el-dialog v-model="showCustomerDialog" title="Customer Details" width="600px">
      <div v-if="selectedCustomer">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="User ID">{{ selectedCustomer.id }}</el-descriptions-item>
          <el-descriptions-item label="Username">{{ selectedCustomer.username }}</el-descriptions-item>
          <el-descriptions-item label="Email">{{ selectedCustomer.email }}</el-descriptions-item>
          <el-descriptions-item label="Role">{{ selectedCustomer.role }}</el-descriptions-item>
          <el-descriptions-item label="Status">
            <el-tag :type="selectedCustomer.isActive ? 'success' : 'danger'">
              {{ selectedCustomer.isActive ? 'Active' : 'Inactive' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="Role">{{ selectedCustomer.role }}</el-descriptions-item>
          <el-descriptions-item label="Created At">{{ formatDate(selectedCustomer.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="Last Login">{{ formatDate(selectedCustomer.lastLoginAt) }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="showCustomerDialog = false">Close</el-button>
      </template>
    </el-dialog>

    <!-- Add Customer Dialog -->
    <el-dialog v-model="showAddCustomerDialog" title="Add New Customer" width="500px">
      <el-form :model="addCustomerForm" label-width="100px">
        <el-form-item label="Email" required>
          <el-input v-model="addCustomerForm.email" type="email" placeholder="Enter email" />
        </el-form-item>
        <el-form-item label="Username" required>
          <el-input v-model="addCustomerForm.username" placeholder="Enter username" />
        </el-form-item>
        <el-form-item label="Password" required>
          <el-input v-model="addCustomerForm.password" type="password" placeholder="Enter password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddCustomerDialog = false">Cancel</el-button>
        <el-button type="primary" @click="handleCreateCustomer" :loading="loading">Create</el-button>
      </template>
    </el-dialog>

    <!-- Edit Customer Dialog -->
    <el-dialog v-model="showEditCustomerDialog" title="Edit Customer" width="500px">
      <el-form :model="editCustomerForm" label-width="100px">
        <el-form-item label="Email" required>
          <el-input v-model="editCustomerForm.email" type="email" placeholder="Enter email" />
        </el-form-item>
        <el-form-item label="Username" required>
          <el-input v-model="editCustomerForm.username" placeholder="Enter username" />
        </el-form-item>
        <el-form-item label="Status">
          <el-switch v-model="editCustomerForm.isActive" active-text="Active" inactive-text="Inactive" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditCustomerDialog = false">Cancel</el-button>
        <el-button type="primary" @click="handleUpdateCustomer" :loading="loading">Update</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useToast } from 'vue-toastification'
import { useAdminStore } from '../stores/admin'
import type { CreateCustomerRequest, UpdateUserRequest } from '../stores/admin'
import { Search, Plus, Refresh } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'

// 类型定义
interface Customer {
  id: number
  username: string
  email: string
  isActive: boolean
  role: string
  createdAt: string
  lastLoginAt?: string
  createdByAdminId?: number | null
}

// 响应式数据
const loading = ref(false)
const searchQuery = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const totalCustomers = ref(0)
const customerList = ref<Customer[]>([])
const showCustomerDialog = ref(false)
const selectedCustomer = ref<Customer | null>(null)
const showAddCustomerDialog = ref(false)
const showEditCustomerDialog = ref(false)

// 表单数据
const addCustomerForm = ref<CreateCustomerRequest>({
  email: '',
  username: '',
  password: ''
})

const editCustomerForm = ref<UpdateUserRequest>({
  userId: 0,
  email: '',
  username: '',
  isActive: true
})

// 工具
const toast = useToast()
const adminStore = useAdminStore()

// 计算属性
const displayCustomers = computed(() => {
  let filtered = customerList.value

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(customer =>
      customer.username.toLowerCase().includes(query) ||
      customer.email.toLowerCase().includes(query)
    )
  }

  // 状态过滤
  if (statusFilter.value) {
    filtered = filtered.filter(customer => {
      if (statusFilter.value === 'active') return customer.isActive
      if (statusFilter.value === 'inactive') return !customer.isActive
      return true
    })
  }

  return filtered
})

// Format date
function formatDate(dateString?: string) {
  if (!dateString) return 'Never'

  const date = new Date(dateString)
  return date.toLocaleDateString('en-US', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// Load customer list
async function loadCustomers() {
  loading.value = true
  try {
    const result = await adminStore.getAllUsers(currentPage.value, pageSize.value)

    // 过滤出普通用户（客户）
    const customers = result.users.filter((user: any) => user.role === 'USER')
    customerList.value = customers as Customer[]
    totalCustomers.value = customers.length

    toast.success('Customer list loaded successfully')
  } catch (error) {
    console.error('Failed to load customers:', error)
    toast.error('Failed to load customer list')
  } finally {
    loading.value = false
  }
}

// Event handlers
function handleAddCustomer() {
  addCustomerForm.value = {
    email: '',
    username: '',
    password: ''
  }
  showAddCustomerDialog.value = true
}

function handleRefresh() {
  loadCustomers()
}

function handleViewCustomer(customer: Customer) {
  selectedCustomer.value = customer
  showCustomerDialog.value = true
}

function handleEditCustomer(customer: Customer) {
  editCustomerForm.value = {
    userId: customer.id,
    email: customer.email,
    username: customer.username,
    isActive: customer.isActive
  }
  showEditCustomerDialog.value = true
}

async function handleToggleStatus(customer: Customer) {
  try {
    loading.value = true
    await adminStore.updateUser({
      userId: customer.id,
      isActive: !customer.isActive
    })

    // 更新本地数据
    const index = customerList.value.findIndex(c => c.id === customer.id)
    if (index !== -1) {
      customerList.value[index].isActive = !customer.isActive
    }

    const action = customer.isActive ? 'disabled' : 'enabled'
    toast.success(`Customer ${customer.username} has been ${action}`)
  } catch (error) {
    console.error('Failed to toggle customer status:', error)
    toast.error('Failed to update customer status')
  } finally {
    loading.value = false
  }
}

// 创建客户
async function handleCreateCustomer() {
  try {
    loading.value = true
    const newCustomer = await adminStore.createCustomer(addCustomerForm.value)

    // 添加到本地列表
    customerList.value.unshift(newCustomer as Customer)
    totalCustomers.value += 1

    showAddCustomerDialog.value = false
    toast.success('Customer created successfully')
  } catch (error) {
    console.error('Failed to create customer:', error)
    toast.error('Failed to create customer')
  } finally {
    loading.value = false
  }
}

// 更新客户
async function handleUpdateCustomer() {
  try {
    loading.value = true
    const updatedCustomer = await adminStore.updateUser(editCustomerForm.value)

    // 更新本地数据
    const index = customerList.value.findIndex(c => c.id === editCustomerForm.value.userId)
    if (index !== -1) {
      customerList.value[index] = updatedCustomer as Customer
    }

    showEditCustomerDialog.value = false
    toast.success('Customer updated successfully')
  } catch (error) {
    console.error('Failed to update customer:', error)
    toast.error('Failed to update customer')
  } finally {
    loading.value = false
  }
}

// 删除客户
async function handleDeleteCustomer(customer: Customer) {
  try {
    await ElMessageBox.confirm(
      `Are you sure you want to delete customer "${customer.username}"?`,
      'Confirm Delete',
      {
        confirmButtonText: 'Delete',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }
    )

    loading.value = true
    await adminStore.deleteUser(customer.id)

    // 从本地列表移除
    const index = customerList.value.findIndex(c => c.id === customer.id)
    if (index !== -1) {
      customerList.value.splice(index, 1)
      totalCustomers.value -= 1
    }

    toast.success('Customer deleted successfully')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete customer:', error)
      toast.error('Failed to delete customer')
    }
  } finally {
    loading.value = false
  }
}

function handleSizeChange(newSize: number) {
  pageSize.value = newSize
  loadCustomers()
}

function handleCurrentChange(newPage: number) {
  currentPage.value = newPage
  loadCustomers()
}

// 组件挂载
onMounted(() => {
  loadCustomers()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.main-content {
  max-width: 1400px;
  margin: 0 auto;
}
</style>
